import threading
import time
from loguru import logger
from typing import Any
import signal
import sys

class MonitorManager:
    _running = True  # 添加类级别的运行状态标志

    @classmethod
    def stop_monitoring(cls):
        """停止监控"""
        cls._running = False

    @staticmethod
    def log_shared_var(start_time: float, shared_var: Any, shared_list: Any) -> None:
        """
        记录共享变量状态
        
        Args:
            start_time: 开始时间
            shared_var: 共享变量
            shared_list: 共享列表
        """
        while MonitorManager._running:
            try:
                current_time = time.time()
                current_value = shared_var.value
                elapsed_time = current_time - start_time
                
                average_increase_per_second = current_value / elapsed_time if elapsed_time > 0 else 0
                
                logger.info(
                    f'已提交总量: {current_value}, '
                    f'经过时间: {elapsed_time} 秒, '
                    f'当前监控直播间数量 {len(shared_list)}, '
                    f'每秒增加量: {average_increase_per_second}'
                )
                time.sleep(5)
            except Exception as e:
                logger.error(f"监控记录错误: {str(e)}")
                break

    @staticmethod
    def start_monitoring(start_time: float, shared_var: Any, shared_list: Any) -> None:
        """
        启动监控
        
        Args:
            start_time: 开始时间
            shared_var: 共享变量
            shared_list: 共享列表
        """
        monitor_thread = threading.Thread(
            target=MonitorManager.log_shared_var,
            args=(start_time, shared_var, shared_list),
            daemon=True
        )
        monitor_thread.start()
        return monitor_thread  # 返回线程对象以便管理 